/*
 * =====================================================================================
 *
 *       Filename:  linkqueue.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  10/31/2010 08:48:24 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *        Company:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "linkqueue.h"


status init_queue(linkqueue *L)
{
    L->front = (QueuePtr)malloc(sizeof(QNode));
    if(!L->front)
        return -1;
    L->rear = L->front;
    L->front->next = NULL;
    return 0;
    
}
status destroy_queue(linkqueue *L)
{
    QueuePtr p, q;
    
    while(p->next != L->rear)
    {
        q = p->next;
        free(p);
        p = q;
    }

    free(L->rear);
    L->front = L->rear = NULL;
    
    return 0;
}

status clear_queue(linkqueue *L)
{
    if(queue_empty(L))
    {
        printf("is empty");
        return -2;
    }
    else
    {
        QueuePtr p,q;
        p = L->front->next;
        while(p!=L->rear)
        {
            q = p->next;
            free(p);
            p = q;
        }
        free(L->rear);
        L->rear = L->front;
        return 0;
    }


}
status queue_empty(linkqueue *L)
{
    return L->front == L->rear;
}
int queue_length(linkqueue *L)
{
    int i;
    if(queue_empty(L))
    {
        printf("is empty");
        return -2;
    }
    else
    {
        QueuePtr p;
        p = L->front->next;

        while(p!=L->rear)
            i++;
        return i;
    }
}
status enqueue(linkqueue *L, lqdata e)
{
    QueuePtr q;
    q = (QueuePtr)malloc(sizeof(QNode));
    if(!q)
        return -1;

    q->data = e;
    q->next = NULL;
    L->rear->next = q;
    L->rear = q;
    return 0;
    

}
status dequeue(linkqueue *L, lqdata *e)
{
    if(queue_empty(L))
    {
        printf("is empty");
        return -2;
    }
    else
    {
        QueuePtr p;
        p = L->front;
        *e = p->data;
        L->front->next = p->next;

        if(L->rear == p)
            L->rear = L->front;

        free(p);
        p = NULL;
        return 0;
    }

}
//status queue_traverse(linkqueue *L, void (*)visit(lqdata) )
//{}

status display(linkqueue *L)
{
    if(queue_empty(L))
    {
        printf("is empty");
        return -2;
    }

    QueuePtr p;
    p = L->front->next;

    while(p)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");

    return 0;
}
